package fwx.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FileUpDownServlet",urlPatterns = "/f")
public class FileUpDownServlet extends BaseServlet {
    public void up(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=utf-8");
            DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工程对象
            File f = new File("c:\\tempFolder");// 缓存目录
            if (!f.exists()) {
                f.mkdirs();
            }
            factory.setRepository(f);// 设置缓存路径
            // 创建上传对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            // 设置字符编码
            fileUpload.setHeaderEncoding("utf-8");
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            PrintWriter writer=response.getWriter();
            for(FileItem fileItem:fileItems) {
                if(fileItem.isFormField()) {
                    //获得字段名
                    String name=fileItem.getFieldName();
                    if(name.equals("name")) {
                        if(!fileItem.getString().equals("")) {
                            String value=fileItem.getString("utf-8");
                            writer.write("上传者"+value);
                        }
                    }
                }else {
                    //获取上传的文件名
                    String fileName=fileItem.getName();
                    writer.write("上传的文件名是："+fileName);
                    fileName= UUID.randomUUID().toString()+"_"+fileName;
                    //服务器上创建同名文件
                    String webPath="/upload/";
                    String filePath=getServletContext().getRealPath(webPath+fileName);
                    File file=new File(filePath);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                    InputStream in=fileItem.getInputStream();
                    FileOutputStream out=new FileOutputStream(file);
                    //流的复制
                    byte[]buff=new byte[1024];
                    int len;
                    while((len=in.read(buff))>0) {
                        out.write(buff,0,len);
                    }
                    in.close();
                    out.close();
                    fileItem.delete();
                    writer.write("上传成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void down(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String fileName=request.getParameter("filename");
        String folder="/upload/";
        response.addHeader("Content-Type", "application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename="+fileName);

        InputStream in=getServletContext().getResourceAsStream(folder+fileName);

        OutputStream out=response.getOutputStream();
        byte []buff=new byte[1024];
        int len;
        while((len=in.read(buff))!=-1) {
            out.write(buff,0,len);
        }
    }
}
